<?php
require_once("config/path_config.php");
$cache_time=10;
$OJ_CACHE_SHARE=false;
require_once('./include/cache_start.php');
require_once('./include/db_info.inc.php');
require_once('./include/setlang.php');
$view_title= "Welcome To Online Judge";
require_once("./include/check_post_key.php");
require_once("./include/my_func.inc.php");

function exitWithErr($errStr)
{
    print "<script language='javascript'>\n";
    echo "alert('";
    echo $errStr;
    print "');\n history.go(-1);\n</script>";
    exit(0);
}

// 用户未登录
if ( !isset($_SESSION['user_id']) ) {
    echo '用户未登录';
    exit(0);
}

$userID = $_SESSION['user_id'];

// 查看原密码是否正确
$oldPasswd=$_POST['opassword'];
$sql="SELECT `user_id`,`password` FROM `users` WHERE `user_id`=?";
$result=pdo_query($sql, $userID);
$row=$result[0];
if ( !$row || !pwCheck($oldPasswd, $row['password']) ) {
    exitWithErr("密码错误");
}

// 查看输入的新密码是否满足要求
$newPasswd = $_POST['npassword'];
$rptNewPasswd = $_POST['rptpassword'];
if ( strlen($newPasswd) < 6 ) {
    exitWithErr("密码长度必须大于6");
}

if ( strcmp($newPasswd, $rptNewPasswd) != 0 ) {
    exitWithErr("两次输入的新密码不一致!");
}

$secretPasswd = pwGen($newPasswd);

// 更新用户密码
$sql="UPDATE `users` SET `password`=? WHERE `user_id`=?";
pdo_query($sql, $secretPasswd, $userID);
unset($_SESSION['need_chg_passwd']);
header("Location: /index.php");
?>
